package com.emapp.lccode.mode

import androidx.lifecycle.MutableLiveData
import com.emapp.lccode.base.BaseApplication
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.bean.DeviceKt
import com.emapp.lccode.bean.MaterialKt
import com.emapp.lccode.bean.OrderKt
import com.emapp.lccode.bean.ProblemTypeKt
import com.emapp.lccode.bean.Project
import com.emapp.lccode.bean.UpFileKt
import com.emapp.lccode.http.apiService
import com.emapp.lccode.utils.XtomLogger
import com.hjq.toast.Toaster
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.state.ResultState
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

open class OrderKtViewModel : BaseViewModel() {
    var orders: MutableLiveData<ResultState<OrderKt>> = MutableLiveData()
    var myorders: MutableLiveData<ResultState<OrderKt>> = MutableLiveData()
    var orderInfor: MutableLiveData<ResultState<ArrayList<OrderKt>>> = MutableLiveData()
    var problemTypes: MutableLiveData<ResultState<ArrayList<ProblemTypeKt>>> = MutableLiveData()
    var device: MutableLiveData<ResultState<ArrayList<DeviceKt>>> = MutableLiveData()
    var file: MutableLiveData<ResultState<UpFileKt>> = MutableLiveData()
    var reportAdd: MutableLiveData<ResultState<Any>> = MutableLiveData()
    var types: MutableLiveData<ArrayList<ProblemTypeKt>> = MutableLiveData()
    var deviceAdd: MutableLiveData<ResultState<Any>> = MutableLiveData()
    var project: MutableLiveData<ResultState<Project>> = MutableLiveData()
    var paidan: MutableLiveData<ResultState<Any>> = MutableLiveData()
    var mateial: MutableLiveData<ResultState<MaterialKt>> = MutableLiveData()
    var reply: MutableLiveData<ResultState<Any>> = MutableLiveData()

    var xunjians: MutableLiveData<ResultState<OrderKt>> = MutableLiveData()

    /**
     * 派给我的工单，首页列表用的
     */
    fun getOrderList(start_time: String, end_time: String, status: String, pager: Int) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.getOrderList(
                u.admin_id, start_time, end_time, status,
                BaseConfig.page_count.toString(), pager.toString()
            )
        }, orders, false)
    }

    /**
     * 我发布的工单，上报记录
     */
    fun getMyReportOrderList(
        device_id: String,
        start_time: String,
        end_time: String,
        status: String,
        keywords: String,
        pager: Int
    ) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.getMyReportOrderList(
                u.admin_id, device_id, start_time, end_time, status, keywords,
                BaseConfig.page_count.toString(), pager.toString()
            )
        }, myorders, false)
    }

    /**
     * 巡检记录
     */
    fun getxunjianList(
        start_time: String,
        end_time: String,
        status: String,
        keywords: String,
        pager: Int
    ) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.getXunjianList(
                u.admin_id, start_time, end_time, status, keywords,
                BaseConfig.page_count.toString(), pager.toString()
            )
        }, xunjians, false)
    }

    fun getOrderInfor(id: String) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.getOrderInfor(
                u.admin_id, id
            )
        }, orderInfor, true)
    }

    fun getXunjianInfor(id: String) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.getXunjianInfor(
                u.admin_id, id
            )
        }, orderInfor, true)
    }

    /**
     * 上报工单
     */
    fun reportAdd(
        question_sta: String,
        form_type: String?,
        work_type: String?,
        son_type: String?,
        admin_id: String,
        device_id: String,
        upload_lnglat: String,
        address: String?,
        detail_type: String,
        station_num: String?,
        approve_type: String?,
        content: String,
        remark: String?,
        file_ids: String,
        copy_uids: String?
    ) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.reportAdd(
                question_sta, form_type, work_type, son_type,
                u.admin_id, device_id, upload_lnglat, address,
                detail_type, station_num, approve_type, content, remark, file_ids, copy_uids
            )
        }, reportAdd, true, "正在提交...")
    }

    /**
     * 获取问题分类
     */
    fun getProblemType(pid: String) {
        request({ apiService.getProblemType(pid) }, problemTypes, true)
    }
//    fun getDeviceType(work_type: String,device_type: String,work_type: String,work_type: String,work_type: String,work_type: String,work_type: String) {
//        request({ apiService.getDeviceTypeList(work_type,device_type) }, device, true)
//    }
    /**
     * 上传图片
     */
    fun upFile(f: File) {
        val builder = MultipartBody.Builder().apply {
            setType(MultipartBody.FORM)
            addFormDataPart("admin_id", BaseApplication.instance.getUser()?.admin_id.toString())
            addFormDataPart("file", f.name, f.asRequestBody("image/*".toMediaTypeOrNull()))
        }
//        builder.setType(MultipartBody.FORM)
//            .addFormDataPart("admin_id",BaseApplication.getInstance().user.admin_id)
//            .addFormDataPart("file", f.name, f.asRequestBody("image/*".toMediaTypeOrNull()))
        request({ apiService.upFile(builder.build()) }, file, false)
    }
    fun upFileFeedBack(f: File) {
        val builder = MultipartBody.Builder().apply {
            setType(MultipartBody.FORM)
            addFormDataPart("admin_id", BaseApplication.instance.getUser()?.admin_id.toString())
            addFormDataPart("file", f.name, f.asRequestBody("image/*".toMediaTypeOrNull()))
        }
        request({ apiService.upFileFeedBack(builder.build()) }, file, false)
    }
    fun upFileDevice(f: File) {
        val builder = MultipartBody.Builder().apply {
            setType(MultipartBody.FORM)
            addFormDataPart("admin_id", BaseApplication.instance.getUser()?.admin_id.toString())
            addFormDataPart("file", f.name, f.asRequestBody("image/*".toMediaTypeOrNull()))
        }
        request({ apiService.upFileDevice(builder.build()) }, file, false)
    }

    /**
     * 设备分类
     */
    fun getDeviceType(pid: String) {
        request({ apiService.getDeviceType(pid) }, {
            var deTypes: ArrayList<ProblemTypeKt> = arrayListOf()
            it.forEach { typeKt ->
                if (typeKt.pid == pid) {
                    deTypes.add(typeKt)
                }
            }
            types.postValue(deTypes)
        }, {
            Toaster.show(it.errorMsg)
        }, true)
    }

    /**
     * 设备详情
     */
    fun getDeviceInfor(work_type: String, id: String) {
        request({
            apiService.getDeviceInfor(work_type, id)
        }, device, true)
    }

    /**
     * 添加编辑设备
     */
    fun addDevice(infor: DeviceKt) {
        val u = BaseApplication.instance.getUser() ?: return
        infor.admin_id = u.admin_id
        request({
            apiService.deviceAdd(
                infor.operation_type,
                infor.id,
                infor.work_type,
                infor.device_type,
                infor.project_id,
                infor.name,
                infor.num_code,
                infor.device_status.toString(),
                infor.question_sta.toString(),
                infor.upload_lnglat,
                infor.address,
                infor.username,
                infor.phone,
                infor.thumb,
                infor.file_ids,
                infor.province,
                infor.city,
                infor.district,
                infor.boxcode,
                infor.imei,
                infor.changjia,
                infor.year,
                infor.buildtime,
                infor.admin_id,
                infor.long_len,
                infor.depth,
                infor.dn_norms,
                infor.width_len,
                infor.remark,
                infor.rongliang,
                infor.check_type,
                infor.bianma_num,
                infor.json_text,
                infor.water_outlet_plug
            )
        }, deviceAdd, true)
    }

    /**
     * 项目列表
     */
    fun getProjectList(
        keywords: String = "",
        year: String = "",
        city_ids: String = "",
        pager: Int = 0
    ) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.getProjectList(
                u.admin_id, keywords, year, city_ids, "80", "0"
            )
        }, project, true)
    }

    /**
     * 派单
     */
    fun paidan(
        check: String = "",
        id: String = "",
        check_admin_ids: String = "",
        check_node: String = "",
        approve_type: String = "1"
    ) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.paidan(
                check,
                u.admin_id, id, check_admin_ids, "1", check_node, approve_type
            )
        }, paidan, true)
    }

    /**
     * 物料列表
     */
    fun getWuLiaoList(
        keywords: String = "",
        pager: Int = 0
    ) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.getWuliaoList(
                u.admin_id, keywords, BaseConfig.page_count.toString(), pager.toString()
            )
        }, mateial, false)
    }

    /**
     * 回复
     */
    fun reply(
        check: String = "",
        id: String = "",
        content: String = "",
        amount: String = "",
        check_node: String = "",
        file_ids: String = "",
        upload_bom: String = ""
    ) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.reply(
                check,
                u.admin_id,
                id,
                "1",
                check_node,
                "",
                content,
                amount,
                file_ids,
                upload_bom
            )
        }, reply, true)
    }

    /**
     * 回复
     */
    fun feedBack(
        content: String = "",
        file_ids: String = ""
    ) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.feedback(
                u.admin_id,
                content,
                content,
                file_ids
            )
        }, reply, true)
    }

    protected val TAG = this.javaClass.simpleName
    open fun log_e(msg: String?) {
        if (BaseConfig.isDebug) XtomLogger.e(TAG, msg)
    }
}